
import requests
from First.DataAccess import utils
from First import views
def shijianfenxi(start_date,end_date):
    def hanneihuoqushuju(start_date, end_date):
        access_token, appkey= utils.huoquyonghujiapi()
        method = 'event/a'
        metrics = 'daily_event_count,daily_event_user_count,average_event_time'
        url = 'https://openapi.baidu.com/rest/2.0/mtj/svc/app/getDataByKey?access_token={access_token}&key={appkey}&method={method}&start-date={start_date}&end-date={end_date}&metrics={metrics}'.format(
            access_token=access_token, appkey=appkey, method=method, start_date=start_date, end_date=end_date,
            metrics=metrics)
        return request_data(url)
    str1 =hanneihuoqushuju(start_date,end_date)
    if 'error_code' in str1:
        utils.gengxinyonghujiapi()
        str1 = hanneihuoqushuju(start_date, end_date)
        if 'error_code' in str1:
            views.hanshurwzanting('rwshijianfenxi')
    if 'error_code' not in str1:
        length = len(str1['result']['items'][0])
        dataqingxi = {}
        dataqingxi['evenid'] = []
        dataqingxi['shijianid'] = []
        dataqingxi['shijianming'] = []
        dataqingxi['chufacishu'] = []
        dataqingxi['chufayonghushu'] = []
        dataqingxi['shijianpingjun'] = []
        # print(len(dataqingxi['shijianid']))
        for num in range(0, length):
            # print(str(str1['result']['items'][0][num][0]['eventName']))
            dataqingxi['evenid'].append(str(str1['result']['items'][0][num][0]['id']))
            dataqingxi['shijianid'].append(str(str1['result']['items'][0][num][0]['eventId']))
            dataqingxi['shijianming'].append(str(str1['result']['items'][0][num][0]['eventName']))
            dataqingxi['chufacishu'].append(
                0 if str1['result']['items'][1][num][0] == "--" else int(str1['result']['items'][1][num][0]))
            dataqingxi['chufayonghushu'].append(
                0 if str1['result']['items'][1][num][1] == "--" else int(str1['result']['items'][1][num][1]))
            dataqingxi['shijianpingjun'].append(
                0 if str1['result']['items'][1][num][2] == "--" else int(str1['result']['items'][1][num][2]))
        return dataqingxi

def request_data(url):
    req = requests.get(url, timeout=30)  # 请求连接
    req_jason = req.json()  # 获取数据
    return req_jason